from celery import Celery
import os
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# Redis 配置
redis_host = os.getenv("REDIS_HOST", "localhost")
redis_port = os.getenv("REDIS_PORT", "6379")
redis_password = os.getenv("REDIS_PASSWORD", "")
redis_db = os.getenv("REDIS_DB", "0")

# 构造 Redis URL
if redis_password:
    redis_url = f"redis://:{redis_password}@{redis_host}:{redis_port}/{redis_db}"
else:
    redis_url = f"redis://{redis_host}:{redis_port}/{redis_db}"

# 创建 Celery 实例
celery_app = Celery(
    "dts-worker",
    broker=redis_url,
    backend=redis_url
)

# Celery 配置
celery_app.conf.update(
    task_serializer="json",
    accept_content=["json"],
    result_serializer="json",
    timezone="UTC",
    enable_utc=True,
    worker_prefetch_multiplier=1,
    task_acks_late=True,
    # Redis连接配置
    broker_connection_retry=True,
    broker_connection_retry_on_startup=True,
    broker_connection_max_retries=10,
    redis_retry_on_timeout=True,
    redis_socket_connect_timeout=30,
    redis_socket_keepalive=True,
    redis_backend_health_check_interval=30,
)

@celery_app.task
def test_task():
    return {"message": "Test task executed successfully"}